package com.epfresh.supplier.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.RequestEntityMapSupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseApplication;
import com.epfresh.api.global.BaseFragment;
import com.epfresh.api.global.BuyerConstant;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.JsonUtils;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.Dialog.BaseDialogView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.supplier.R;
import com.epfresh.supplier.activity.AgencyListActivity;
import com.epfresh.supplier.activity.BaseProductDetailActivity;
import com.epfresh.supplier.activity.BaseStoreInfoActivity;
import com.epfresh.supplier.activity.GrouponInfoActivity;
import com.epfresh.supplier.activity.HomeActivity;
import com.epfresh.supplier.activity.MakeAgentActivity;
import com.epfresh.supplier.activity.OrderAgentActivity;
import com.epfresh.supplier.activity.OrderOnGroupActivity;
import com.epfresh.supplier.activity.WebActivity;
import com.epfresh.supplier.adapter.HomeBuyerCityItemViewBinder;
import com.epfresh.supplier.adapter.HomeBuyerItemViewBinder;
import com.epfresh.supplier.adapter.HomeBuyerTitleViewBinder;
import com.epfresh.supplier.adapter.HomeBuyerTopViewBinder;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.dialog.FilterCategoryDialog;
import com.epfresh.supplier.dialog.FilterCityDialog;
import com.epfresh.supplier.entity.AgencyListItem;
import com.epfresh.supplier.entity.BuyerFilter;
import com.epfresh.supplier.entity.ContentEntity;
import com.epfresh.supplier.entity.Groupon;
import com.epfresh.supplier.entity.HomeBuyer;
import com.epfresh.supplier.entity.HomeBuyerNumber;
import com.epfresh.supplier.entity.MerChantInfo;
import com.epfresh.supplier.entity.MerchantMember;
import com.epfresh.supplier.entity.StaffInfo;
import com.epfresh.supplier.entity.TitleBean;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;
import multitype.loadmore.LoadMoreDelegate;
import multitype.loadmore.LoadMoreItem;
import multitype.loadmore.LoadMoreViewBinder;

/**
 * Created by zzq on 2017/12/4.
 */
public class HomeBuyerFragment extends BaseFragment implements FilterCityDialog.SelectCondition {

    //列表数据
    List<Object> mItems = new ArrayList<>();
    MultiTypeAdapter mMultiAdapter;
    HomeBuyerTitleViewBinder titleViewBinder;
    HomeBuyerTopViewBinder topViewBinder;
    HomeBuyerItemViewBinder itemViewBinder;
    HomeBuyerCityItemViewBinder itemBuyerCityViewBinder;
    LinearLayoutManager mManager;
    RecyclerView rv;
    private String storeId;//基地店铺id
    LoadMoreDelegate loadMoreDelegate = new LoadMoreDelegate();

    int pageNum = -1;

    private View llTitle, llCity, llCategory;
    private TextView tvCity, tvCategory;
    private ImageView ivCategory, ivCity;
    private int mSuspensionPosition = 1;

    private int dialogHeight = 0;

    String cityId = "", cityName = "城市";
    String categoryId = "", categoryName = "品类";
    TitleBean titleBean = new TitleBean();

    HomeBuyerNumber homeBuyerNumber = new HomeBuyerNumber();

    @Override
    public void selectCity(String condition, String name) {
        cityId = condition;
        cityName = name;
        reqSupplyStoreDyn(0);
        commonDismiss();
    }

    @Override
    public void selectCategory(String condition, String name) {
        categoryId = condition;
        categoryName = name;
        reqSupplyStoreDyn(0);
        commonDismiss();
    }


    @Override
    public String getBaseTag() {
        return Constant.TAG_HOME_FRAGMENT;
    }


    private LoadMoreDelegate.LoadMoreSubject loadMoreSubject = new LoadMoreDelegate.LoadMoreSubject() {
        @Override
        public boolean canLoad() {
            return !ptrFrameLayout.isRefreshing() && pageNum > -1;
        }

        @Override
        public void onLoadMore() {
            loadMoreDelegate.setStatusLoading();
            reqSupplyStoreDyn(pageNum + 1);
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (itemBuyerCityViewBinder != null)
            itemBuyerCityViewBinder.timerStop();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_home_buyer,
                container, false);
    }

    private PtrFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, rv, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            updateReqData();
        }
    };

    //用户刷新的时候要刷新的接口
    public void updateReqData() {
        if (getActivity() != null) {
            reqMerchantList();
            requestMainCnt();
//            reqSupplyStoreDyn(0);
            reqHomePageProductFilter();
        }
    }

    private void initHeadView(View v) {
        ptrFrameLayout = (PtrFrameLayout) v.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
    }

    @Override
    public void onViewCreated(View v, Bundle savedInstanceState) {
        super.onViewCreated(v, savedInstanceState);
        reqHomePageProductFilter();
        initHeadView(v);
        rv = (RecyclerView) v.findViewById(R.id.home_buyer_fragment_rv);
        llTitle = v.findViewById(R.id.ll_title);
        llCity = v.findViewById(R.id.ll_city);
        llCategory = v.findViewById(R.id.ll_category);
        tvCity = v.findViewById(R.id.home_buyer_fragment_title_city_tv);
        tvCategory = v.findViewById(R.id.tv_category);
        ivCategory = v.findViewById(R.id.iv_category);
        ivCity = v.findViewById(R.id.iv_city);

        llCategory.setOnClickListener(this);
        llCity.setOnClickListener(this);

        mManager = new LinearLayoutManager(getContext());

        rv.setLayoutManager(mManager);

        mMultiAdapter = new MultiTypeAdapter();

        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        loadMoreDelegate.attach(rv, loadMoreSubject);

        itemBuyerCityViewBinder = new HomeBuyerCityItemViewBinder();

        itemBuyerCityViewBinder.setOnBuyerListener(new HomeBuyerCityItemViewBinder.OnBuyerListener() {
            @Override
            public void onBuyer(View view, int position, Groupon data) {
                //我要买首页有拼货进度的商品，点击该进度的拼货，不需要进入代办列表，请修正
                storeId=data.getBaseStoreId();//应老宋要求在拼货时，把商品所在基地id传递过去，点击的时候就把基地店铺的id设置成全局
                intoGrouponInfo(data.getGrouponId(), data.getProductId(),data);
            }
        });
        itemViewBinder = new HomeBuyerItemViewBinder();
        itemViewBinder.setOnBuyerListener(new HomeBuyerItemViewBinder.OnBuyerListener() {
            @Override
            public void onBuyer(View view, int position, HomeBuyer data) {
                storeId=data.getBaseStoreId();
                intoGrouponInfo(null, data.getId(),null);
            }
        });
        itemViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if (data instanceof HomeBuyer) {
                    switch (view.getId()) {
                        case R.id.rl_base:
                            HomeBuyer info = (HomeBuyer) data;
                            intoBaseStore(info.getBaseStoreId());
                            break;
                        case R.id.rl_product:
                            intoProductDetail((HomeBuyer) data);
                            break;
                    }
                } else {
                    return;
                }
            }
        });
        titleViewBinder = new HomeBuyerTitleViewBinder();
        titleViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if (view.getId() == R.id.ll_category) {
                    llCategory.performClick();
                } else {
                    llCity.performClick();
                }
            }
        });
        topViewBinder = new HomeBuyerTopViewBinder();
        topViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                Intent intent;
                switch (view.getId()) {
                    case R.id.tv_into_goods:
                        intent = new Intent(getContext(), WebActivity.class);
                        intent.putExtra(Constant.KEY_WEB_URL, Constant.URL_HELP_BUYER_HOME);
                        intent.putExtra(Constant.KEY_WEB_TITLE, getString(R.string.help));
                        startActivity(intent);
                        break;
                    case R.id.tv_order_agent:
                        intent = new Intent(getAppActivity(), OrderAgentActivity.class);
                        intent.putExtra("orderType", 1);
                        startActivity(intent);
                        break;
                    case R.id.tv_order_together:
                        intent = new Intent(getAppActivity(), OrderOnGroupActivity.class);
                        intent.putExtra("orderType", 0);
                        startActivity(intent);
                        break;
                    case R.id.tv_make_agent:
                        intent = new Intent(getAppActivity(), MakeAgentActivity.class);
                        startActivity(intent);
                        break;
                }
            }
        });

        mMultiAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        mMultiAdapter.register(HomeBuyerNumber.class, topViewBinder);
        mMultiAdapter.register(TitleBean.class, titleViewBinder);
        mMultiAdapter.register(HomeBuyer.class, itemViewBinder);
        mMultiAdapter.register(Groupon.class, itemBuyerCityViewBinder);
        mItems.add(homeBuyerNumber);
        mItems.add(titleBean);
        rv.setAdapter(mMultiAdapter);

        mMultiAdapter.setItems(mItems);
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                commonDismiss();
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                commonDismiss();
                View view = mManager.findViewByPosition(mSuspensionPosition);
                if (view != null) {
                    if (view.getTop() <= 0) {
                        llTitle.setVisibility(View.VISIBLE);
                        dialogHeight = llTitle.getBottom();
                    } else {
                        llTitle.setVisibility(View.GONE);
                        dialogHeight = view.getBottom();
                    }
                } else {
                    llTitle.setVisibility(View.VISIBLE);
                    dialogHeight = llTitle.getHeight();
                }
            }
        });
        requestMainCnt();
        reqSupplyStoreDyn(0);
    }

    private void intoGrouponInfo(String grouponId, String productId,Groupon data) {
        reqProductAgencyStores(grouponId, productId, data);
    }

    private void intoGrouponInfoPage(String grouponId, String productId, AgencyListItem item) {
//        item.getBaseStoreI
        Intent intent = new Intent(getContext(), GrouponInfoActivity.class);
        intent.putExtra("grouponId", grouponId);
        intent.putExtra("productId", productId);
        intent.putExtra("isSingle", true);
        intent.putExtra("storeId",storeId);
        intent.putExtra("agencyItem", JsonUtils.toJson(item));
        startActivity(intent);
    }

    private void intoGrouponInfoPage2(String grouponId, String productId) {
        Intent intent = new Intent(getContext(), GrouponInfoActivity.class);
        intent.putExtra("zanting","zanting");
        intent.putExtra("grouponId", grouponId);
        intent.putExtra("productId", productId);
        intent.putExtra("isSingle", true);
        intent.putExtra("storeId",storeId);
        startActivity(intent);
    }

    private void intoAgencyPage(String grouponId, String productId) {
        Intent intent = new Intent(getContext(), AgencyListActivity.class);
        intent.putExtra("storeId", storeId);
        intent.putExtra("grouponId", grouponId);
        intent.putExtra("productId", productId);
        startActivity(intent);
    }

    private void intoProductDetail(HomeBuyer data) {
        Intent intent = new Intent(getContext(), BaseProductDetailActivity.class);
        intent.putExtra("baseStoreId", data.getBaseStoreId());
        intent.putExtra("productId", data.getId());
        startActivity(intent);
    }

    public void updateDataFirst() {
        if (pageNum == 0) {
            reqSupplyStoreDyn(0);
        }
    }

    public void updateData() {
        if (getActivity() != null) {
            ptrFrameLayout.postDelayed(new Runnable() {
                @Override
                public void run() {
                    rv.scrollToPosition(0);
                    ptrFrameLayout.autoRefresh(true);
                }
            }, 200);
        }
    }

    protected void intoBaseStore(String baseStoreId) {
        Intent intent = new Intent(getContext(), BaseStoreInfoActivity.class);
        intent.putExtra("baseStoreId", baseStoreId);
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_city:
                commonDismiss();
                openCityDialog();
                break;
            case R.id.ll_category:
                commonDismiss();
                openCategoryDialog();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0x002) {// && resultCode == 0x001) {
            // initNotice();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void commonDismiss() {
        if (filterCityDialog != null)
            filterCityDialog.dismiss();
        if (filterCategoryDialog != null)
            filterCategoryDialog.dismiss();
    }

    private FilterCityDialog filterCityDialog;

    private void openCityDialog() {
        if (buyerFilter == null) {
            T.toast("没有加载到筛选信息，请刷新后重试");
            return;
        }
        if (filterCityDialog == null) {
            filterCityDialog = new FilterCityDialog(getContext());
            filterCityDialog.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    tvCity.setTextColor(Color.parseColor("#434343"));
                    tvCity.setText(cityName);
                    ivCity.setImageResource(R.mipmap.select_down);
                    titleBean.upPosition = 0;
                    titleBean.cityName = cityName;
                    Log.e("dismiss", "____" + cityName);
                    mMultiAdapter.notifyItemChanged(1);
                }
            });
            filterCityDialog.setSelectCondition(this);
            tvCity.setTextColor(Color.RED);
            ivCity.setImageResource(R.mipmap.select_up);
            titleBean.upPosition = 1;
            titleBean.cityName = cityName;
            mMultiAdapter.notifyItemChanged(1);
            filterCityDialog.show(buyerFilter.getCities(), dialogHeight);
        } else {
            if (filterCityDialog.isShowing()) {
                filterCityDialog.dismiss();
            } else {
                filterCityDialog.show(buyerFilter.getCities(), dialogHeight);
                filterCityDialog.setCitySelect(cityName);
                tvCity.setTextColor(Color.RED);
                titleBean.upPosition = 1;
                titleBean.cityName = cityName;
                mMultiAdapter.notifyItemChanged(1);
                ivCity.setImageResource(R.mipmap.select_up);
            }
        }
    }

    private FilterCategoryDialog filterCategoryDialog;

    private void openCategoryDialog() {
        if (buyerFilter == null) {
            T.toast("没有加载到筛选信息，请刷新后重试");
            return;
        }
        if (filterCategoryDialog == null) {
            filterCategoryDialog = new FilterCategoryDialog(getContext());
            filterCategoryDialog.setOnDismissListener(new BaseDialogView.OnDismissListener() {
                @Override
                public void onDismiss(Object o) {
                    tvCategory.setTextColor(Color.parseColor("#434343"));
                    tvCategory.setText(categoryName);
                    ivCategory.setImageResource(R.mipmap.select_down);
                    titleBean.upPosition = 0;
                    titleBean.categoryName = categoryName;
                    mMultiAdapter.notifyItemChanged(1);
                }
            });
            tvCategory.setTextColor(Color.RED);
            ivCategory.setImageResource(R.mipmap.select_up);
            filterCategoryDialog.setSelectCondition(this);
            titleBean.upPosition = 2;
            titleBean.categoryName = categoryName;
            mMultiAdapter.notifyItemChanged(1);
            filterCategoryDialog.show(buyerFilter.getNames(), dialogHeight);
        } else {
            if (filterCategoryDialog.isShowing()) {
                filterCategoryDialog.dismiss();
            } else {
                tvCategory.setTextColor(Color.RED);
                ivCategory.setImageResource(R.mipmap.select_up);
                titleBean.upPosition = 2;
                titleBean.categoryName = categoryName;
                mMultiAdapter.notifyItemChanged(1);
                filterCategoryDialog.show(buyerFilter.getNames(), dialogHeight);
                filterCategoryDialog.setCategorySelect(categoryName);
            }
        }
    }

    private List<HomeBuyer> mHomeBuyers = new ArrayList<>();

    /**
     * 我要买商品列表
     * 12.17
     *
     * @param pageNum
     */
    private void reqSupplyStoreDyn(int pageNum) {
        if (getActivity() == null) {
            return;
        }
        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
//        RequestEntityMapSupply.setCmd("supplier/product/list");
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_PRODUCT_LIST);
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        RequestEntityMapSupply.putParameter("pageNumber", pageNum);
        RequestEntityMapSupply.putParameter("hasAgent", 1);
        RequestEntityMapSupply.putParameter("pageSize", 10);
        RequestEntityMapSupply.putParameter("areaCode", cityId);
        RequestEntityMapSupply.putParameter("categoryiiiId", categoryId);
//        request(RequestEntityMapSupply, "supplier/product/list", onSupplyStoreDynRequestListener);
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_PRODUCT_LIST, onSupplyStoreDynRequestListener);
    }

    private OnRequestListener<ContentEntity<HomeBuyer>> onSupplyStoreDynRequestListener = new OnRequestListener<ContentEntity<HomeBuyer>>() {
        @Override
        public ContentEntity<HomeBuyer> jsonToObj(String responseStr) {
            return JsonUtils.fromJsonObject(responseStr, ContentEntity.class, HomeBuyer.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            if (getActivity() == null) {
                return;
            }
            ptrFrameLayout.refreshComplete();
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            if (getActivity() == null) {
                return;
            }
            ptrFrameLayout.refreshComplete();
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<HomeBuyer>> response, Object tag) {
            if (getActivity() == null) {
                return;
            }
            ptrFrameLayout.refreshComplete();
            ContentEntity<HomeBuyer> responseElement = response.getResponseElement();
            boolean last = responseElement.getLast();
            int number = responseElement.getNumber();
            List<HomeBuyer> content = responseElement.getContent();
            //第一页
            if (number == 0) {
                mHomeBuyers.clear();
                mItems.clear();
                mItems.add(homeBuyerNumber);
                mItems.add(titleBean);
            }
            pageNum = number;
            boolean isGrouponList = false;
            if (content != null) {
                int size = content.size();
                for (int i = 0; i < size; i++) {
                    HomeBuyer homeBuyer = content.get(i);
                    List<Groupon> groupon = homeBuyer.getGroupon();
                    mHomeBuyers.add(homeBuyer);
                    mItems.add(homeBuyer);
                    if (groupon != null) {
                        int size1 = groupon.size();
                        if (size1 > 0) {
                            isGrouponList = true;
                        }
                        for (int j = 0; j < size1; j++) {
                            Groupon grouponItem = groupon.get(j);
                            grouponItem.setProductId(homeBuyer.getId());
                            grouponItem.setBaseStoreId(homeBuyer.getBaseStoreId());
                            grouponItem.setChargeUnit(homeBuyer.getChargeUnit());
                            if (j == size1 - 1) {
                                grouponItem.setLast(true);
                            } else {
                                grouponItem.setLast(false);
                            }
                            mItems.add(grouponItem);
                        }
                    }
                }
            }

            if (mHomeBuyers.size() == 0) {
                loadMoreDelegate.setStatusEmpty();
                loadMoreDelegate.addLoadItemOnly(mItems);
            } else {
                loadMoreDelegate.addLoadItemOnly(mItems);
                //最后一个
                if (last) {
                    loadMoreDelegate.setStatusNoMore();
                } else {
                    loadMoreDelegate.setStatusNormal();
                }
            }
            mMultiAdapter.notifyDataSetChanged();
            if (isGrouponList) {
                itemBuyerCityViewBinder.timerStart();
            } else {
                itemBuyerCityViewBinder.timerStop();

            }
        }
    };
    private BuyerFilter buyerFilter;

    /**
     * 我要买商品筛选条件
     * 12.20
     */
    private void reqHomePageProductFilter() {
        if (getActivity() == null) {
            return;
        }

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
//        RequestEntityMapSupply.setCmd("buy/homepage/filters");
        RequestEntityMapSupply.setCmd(BuyerConstant.CMD_BUYER_HOMEPAGE_FILTERS);
        RequestEntityMapSupply.putParameter("all", 0);
        RequestEntityMapSupply.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        requestBuyer(RequestEntityMapSupply, BuyerConstant.CMD_BUYER_HOMEPAGE_FILTERS, onSupplyFilterRequestListener);
    }

    private OnRequestListener<BuyerFilter> onSupplyFilterRequestListener = new OnRequestListener<BuyerFilter>() {
        @Override
        public BuyerFilter jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, BuyerFilter.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<BuyerFilter> response, Object tag) {
            if (getActivity() == null) {
                return;
            }
            buyerFilter = response.getResponseElement();

            //本地手动添加城市"全部"选项的假数据
            BuyerFilter.CitiesBean citiesBean = new BuyerFilter.CitiesBean();
            citiesBean.setCode("");
            citiesBean.setName("全部");
            citiesBean.setSelectFlag(false);
            buyerFilter.getCities().add(0,citiesBean);

            //手动添加品类"全部"选项假数据
            BuyerFilter.NamesBean namesBean = new BuyerFilter.NamesBean();
            namesBean.setName("");
            namesBean.setId("");

            List<BuyerFilter.NamesBean.ChildBean> child = new ArrayList<>();
            BuyerFilter.NamesBean.ChildBean childBean = new BuyerFilter.NamesBean.ChildBean();
            childBean.setId("");
            childBean.setName("全部");
            childBean.setSelectFlag(false);
            child.add(childBean);

            namesBean.setChild(child);
            buyerFilter.getNames().add(0,namesBean);
        }
    };
    private boolean isLockAgency;

    /**
     * 我要买拼货时,选择代办店铺列表
     * 12.95
     *
     * @param grouponId
     * @param productId
     */
    private void reqProductAgencyStores(final String grouponId, final String productId, final Groupon grouponBean ) {
        if (isLockAgency) {
            return;
        }
        isLockAgency = true;
        RequestEntityMapSupply data = new RequestEntityMapSupply();
//        data.setCmd("buy/product/agent/stores");
        data.setCmd(BuyerConstant.CMD_BUYER_PRODUCT_AGENT_STORES);
        data.setClientIdentifierCode(getAppApplication().getClientIdentifierCode());
        data.setStoreId(BaseApplication.getInstance().getStoreId());
        data.putParameter("agentStoreId", BaseApplication.getInstance().getStoreId());
        data.putParameter("grouponId", grouponId);
        data.putParameter("productId", productId);
        requestBuyer(data, BuyerConstant.CMD_BUYER_PRODUCT_AGENT_STORES, new OnRequestListener<List<AgencyListItem>>() {
            @Override
            public List<AgencyListItem> jsonToObj(String responseStr) {
                return JsonUtils.fromJsonList(responseStr, AgencyListItem.class);
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                isLockAgency = false;
                hideProgressDialog();
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                hideProgressDialog();
                isLockAgency = false;
            }

            @Override
            public void onStart(Object tag) {
                showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<List<AgencyListItem>> response, Object tag) {
                List<AgencyListItem> responseElement = response.getResponseElement();
                hideProgressDialog();
                isLockAgency = false;
                if (responseElement != null) {
                    if (grouponId == null) {//跳转到选择哪一个代办的页面
                        if (responseElement.size() != 0) {
                            if (responseElement.size() == 1) {
                                AgencyListItem item = responseElement.get(0);
                                intoGrouponInfoPage(grouponId, productId, item);
                            } else {
                                intoAgencyPage(grouponId, productId);
                            }
                        } else {
                            Toast.makeText(HomeBuyerFragment.this.getContext(), "该商品未找到代办店铺信息，请刷新后重试!", Toast.LENGTH_SHORT).show();
                        } 
                    } else {
                        intoGrouponInfoPage2(grouponId, productId);
//                        if (responseElement.size() > 0) {
//                            for (AgencyListItem item : responseElement) {
//                                if (item.getId().equals(grouponBean.getAgencyStoreId())) {
////                                    intoGrouponInfoPage(grouponId, productId, item);
//                                }
//                            }
//                        } else {
//                            //防止出现不能跳转的情况
//                            intoAgencyPage(grouponId, productId);
//                        }
                    }
                }
            }
        });
    }


    OnRequestListener<HomeBuyerNumber> onRequestListener = new OnRequestListener<HomeBuyerNumber>() {
        @Override
        public HomeBuyerNumber jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, HomeBuyerNumber.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            Log.e(arg + "", "" + HttpRequest.FAIL_NET_FAULT);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            Log.e(arg + "", "" + HttpRequest.FAIL_NET_FAULT);
        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<HomeBuyerNumber> response, Object tag) {
            hideProgressDialog();
            HomeBuyerNumber responseElement = response.getResponseElement();
            homeBuyerNumber = responseElement;
            reqSupplyStoreDyn(0);
//            mMultiAdapter.notifyItemChanged(0);
        }
    };
    private String cmdOrderDetails = "pm-order/baseorder/order/mainCnt";

    public void requestMainCnt() {
        RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
        entity.setCmd(cmdOrderDetails);
        Map<String, String> map = new HashMap<>();
        map.put("buyerStoreId", BaseApplication.getInstance().getStoreId());
        entity.setParameters(map);
        request(entity, cmdOrderDetails, onRequestListener);
    }


    public void reqMerchantList() {

        if (getActivity() == null) {
            return;
        }

        RequestEntityMapSupply RequestEntityMapSupply = new RequestEntityMapSupply();
        RequestEntityMapSupply.setCmd(com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_merchant_afterLogin);

        request(RequestEntityMapSupply, com.epfresh.api.constant.AppSupplyRouterConstant.cmd_account_merchant_afterLogin, onMerchantRequestListener);
    }

    private OnRequestListener<List<MerChantInfo>> onMerchantRequestListener = new OnRequestListener<List<MerChantInfo>>() {
        @Override
        public List<MerChantInfo> jsonToObj(String responseStr) {
            MerchantMember merchantMember = JsonUtils.fromJson(responseStr, MerchantMember.class);
            ArrayList<String> disabledResources = null;
            List<MerChantInfo> mcis = new ArrayList<MerChantInfo>();
            if (merchantMember != null) {
                List<StaffInfo> list = merchantMember.getEmployees();
                disabledResources = merchantMember.getDisabledResources();

                if (list != null)
                    for (int i = 0; i < list.size(); i++) {
                        StaffInfo staffInfo = list.get(i);
                        if (staffInfo != null) {
                            MerChantInfo mc = staffInfo.getMerchant();
                            if (mc != null) {
                                staffInfo.setMerchant(null);

                                mc.setStaffInfo(staffInfo);
                                if (mc.isOwned()) {
                                    mc.setDisabledResources(disabledResources);
                                }
                                mcis.add(mc);
                            }
                        }
                    }

            }


            BaseApplication.getInstance().updateMerchants(mcis);
            BaseApplication.getInstance().putMerchantDisabledResources(disabledResources);
            return mcis;
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {

        }

        @Override
        public void onStart(Object tag) {
        }

        @Override
        public void onResponse(ResponseEntity<List<MerChantInfo>> response, Object tag) {
            FragmentActivity activity = getActivity();
            if (activity != null && activity instanceof HomeActivity) {
               // ((HomeActivity) activity).updateBuyerStatus();
            }
        }
    };


}
